//
//  FileOperation.m
//  PrivateCloud
//
//  Created by Visitor on 10/13/13.
//  Copyright (c) 2013 sarah doo. All rights reserved.
//

#import "FileOperation.h"
#import "AppUtil.h"
#import "DDFolderInfo.h"
#import "DDFileInfo.h"
#import "DDCommentDic.h"
#import "DDConstants.h"

@implementation FileOperation
{
    NSFileManager *_fileManager;
}

- (id)init
{
    self = [super init];
    if(self)
    {
        _fileManager = [NSFileManager defaultManager];
    }
    return self;
}

- (void)deleteFileById:(int)uid{
    DDFileInfo *fileInfo = [DDConstants getLocalFileInfoById:uid];
    //获取文件的类型
    NSString * type = [DDConstants getFileInfoType:[fileInfo fileName]];
    NSString* filePath = [NSString stringWithFormat:@"%@%@/%@",[AppUtil getDocPath],type,[fileInfo fileName]];
    [_fileManager removeItemAtPath:filePath error:nil];
}

- (void)createDirectory
{
    
    NSError *error = nil;
    NSString* photoPath = [NSString stringWithFormat:@"%@music",[AppUtil getDocPath]];
    if (![_fileManager fileExistsAtPath:photoPath]) {
        [_fileManager createDirectoryAtPath:[NSString stringWithFormat:@"%@%@",[AppUtil getDocPath],CLOUD_MUSIC] withIntermediateDirectories:YES attributes:nil error:&error];
        [_fileManager createDirectoryAtPath:[NSString stringWithFormat:@"%@%@",[AppUtil getDocPath],CLOUD_VIDEO] withIntermediateDirectories:YES attributes:nil error:&error];
        [_fileManager createDirectoryAtPath:[NSString stringWithFormat:@"%@%@",[AppUtil getDocPath],CLOUD_PHOTO] withIntermediateDirectories:YES attributes:nil error:&error];
        [_fileManager createDirectoryAtPath:[NSString stringWithFormat:@"%@%@",[AppUtil getDocPath],CLOUD_FILE] withIntermediateDirectories:YES attributes:nil error:&error];
    };
    
    
    
}


- (NSArray *)searchAllFiles
{
    NSMutableArray *allFiles = [[NSMutableArray alloc] init];
    NSError *error = nil;
    //fileList便是包含有该文件夹下所有文件的文件名及文件夹名的数组
    //NSArray *folders = [_fileManager contentsOfDirectoryAtPath:[AppUtil getDocPath] error:&error];
    NSMutableArray *folders = [[NSMutableArray alloc]init];
    //这里不再扫描图片文件夹，而是扫描系统相册
    //    [folders addObject:@"photo"];
    [folders addObject:@"music"];
    [folders addObject:@"video"];
    [folders addObject:@"file"];
    for(NSString *str in folders)
    {
        DDFolderInfo *folderInfo = [[DDFolderInfo alloc] init];
        [folderInfo setName:str];
        [folderInfo setPath:[NSString stringWithFormat:@"%@%@/",[AppUtil getDocPath],str]];
        NSArray *subFiles = [_fileManager contentsOfDirectoryAtPath:[folderInfo path] error:&error];
        [folderInfo setCount:[subFiles count]];
        NSMutableArray *files = [[NSMutableArray alloc] init];
        
        //FIX ME用于扫描图片文件的代码
        ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc]init];//生成整个photolibrary句柄的实例
        NSMutableArray *mediaArray = [[NSMutableArray alloc]init];//存放media的数组
        [assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {//获取所有group
            [group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {//从group里面
                NSString* assetType = [result valueForProperty:ALAssetPropertyType];
                if ([assetType isEqualToString:ALAssetTypePhoto]) {
                    DDFileInfo *fileInfo = [[DDFileInfo alloc]init];
                    
                    NSLog(@"Photo");
                    NSDictionary *assetUrls = [result valueForProperty:ALAssetPropertyURLs];
                    NSDictionary *test = [result valueForProperty:ALAssetPropertyRepresentations];
                    NSLog(@"name------%@",[[result valueForProperty:ALAssetPropertyRepresentations]objectAtIndex:0]);
                    NSUInteger assetCounter = 0;
                    for (NSString *assetURLKey in assetUrls) {
                        NSLog(@"Asset URL %lu = %@",(unsigned long)assetCounter,[assetUrls objectForKey:assetURLKey]);
                        [fileInfo setFilePath:[assetUrls objectForKey:assetURLKey]];
                        [fileInfo setFileLength:[[result defaultRepresentation]size]];
                        [fileInfo setFileId:[DDConstants getGloalId]];
                        [fileInfo setFileName:[[result valueForProperty:ALAssetPropertyRepresentations]objectAtIndex:0]];
                        int nextId = [DDConstants getGloalId] + 1;
                        [DDConstants setGloalId:nextId];
                        [DDConstants addFile:fileInfo andCode:LOCAL_CODE];
                    }
                    
                    NSLog(@"Representation Size = %lld",[[result defaultRepresentation]size]);
                    
                }else if([assetType isEqualToString:ALAssetTypeVideo]){
                    NSLog(@"Video");
                }else if([assetType isEqualToString:ALAssetTypeUnknown]){
                    NSLog(@"Unknow AssetType");
                }
                
            }];
        } failureBlock:^(NSError *error) {
            NSLog(@"Enumerate the asset groups failed.");
        }];
        
        for(NSString *name in subFiles)
        {
            
            DDFileInfo *fileInfo = [[DDFileInfo alloc] init];
            //fileInfo.fileId =
            [fileInfo setFilePath:[NSString stringWithFormat:@"%@%@",[folderInfo path],name]];
            [fileInfo setFileName:name];
            NSDictionary* dirAttr = [_fileManager attributesOfItemAtPath:[fileInfo filePath] error:nil];
            NSUInteger fileLength = [[dirAttr objectForKey:@"NSFileSize"] intValue];
            
            [fileInfo setFileLength:fileLength];
            [files addObject:fileInfo];
            [fileInfo release];
            [fileInfo setFileId:[DDConstants getGloalId]];
            int nextId = [DDConstants getGloalId] + 1;
            [DDConstants setGloalId:nextId];
            [DDConstants addFile:fileInfo andCode:LOCAL_CODE];
            
        }
        [folderInfo setFiles:files];
        [folderInfo setCount:[files count]];
        [files release];
        [allFiles addObject:folderInfo];
        [folderInfo release];
    }
    
    
    return allFiles;
}

- (NSArray *)searchAllFiles:(void (^)(void))completion
{
    NSMutableArray *allFiles = [[NSMutableArray alloc] init];
    [allFiles addObject:@""];
    [allFiles addObject:@""];
    [allFiles addObject:@""];
    [allFiles addObject:@""];
    NSError *error = nil;
    //fileList便是包含有该文件夹下所有文件的文件名及文件夹名的数组
    //NSArray *folders = [_fileManager contentsOfDirectoryAtPath:[AppUtil getDocPath] error:&error];
    NSMutableArray *folders = [[NSMutableArray alloc]init];
    //这里不再扫描图片文件夹，而是扫描系统相册
    //    [folders addObject:@"photo"];
    [folders addObject:@"music"];
    [folders addObject:@"video"];
    [folders addObject:@"file"];
    int count = 0;
    for(NSString *str in folders)
    {
        DDFolderInfo *folderInfo = [[DDFolderInfo alloc] init];
        [folderInfo setName:str];
        [folderInfo setPath:[NSString stringWithFormat:@"%@%@/",[AppUtil getDocPath],str]];
        NSArray *subFiles = [_fileManager contentsOfDirectoryAtPath:[folderInfo path] error:&error];
        [folderInfo setCount:[subFiles count]];
        NSMutableArray *files = [[NSMutableArray alloc] init];
        
        
        for(NSString *name in subFiles)
        {
            
            DDFileInfo *fileInfo = [[DDFileInfo alloc] init];
            //fileInfo.fileId =
            [fileInfo setFilePath:[NSString stringWithFormat:@"%@%@",[folderInfo path],name]];
            [fileInfo setFileName:name];
            NSDictionary* dirAttr = [_fileManager attributesOfItemAtPath:[fileInfo filePath] error:nil];
            NSUInteger fileLength = [[dirAttr objectForKey:@"NSFileSize"] intValue];
            
            [fileInfo setFileLength:fileLength];
            [files addObject:fileInfo];
            [fileInfo release];
            [fileInfo setFileId:[DDConstants getGloalId]];
            int nextId = [DDConstants getGloalId] + 1;
            [DDConstants setGloalId:nextId];
            [DDConstants addFile:fileInfo andCode:LOCAL_CODE];
            
        }
        [folderInfo setFiles:files];
        [folderInfo setCount:[files count]];
        [files release];
        //        [allFiles addObject:folderInfo];
        [allFiles setObject:folderInfo atIndexedSubscript:(count+1)];
        [folderInfo release];
        count ++ ;
        //FIX ME用于扫描图片文件的代码
        
    }
    ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc]init];//生成整个photolibrary句柄的实例
    NSMutableArray *mediaArray = [[NSMutableArray alloc]init];//存放media的数组
    DDFolderInfo* photoInfo = [[DDFolderInfo alloc]init];
    [assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {//获取所有group
        
        [group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {//从group里面
            NSString* assetType = [result valueForProperty:ALAssetPropertyType];
            if ([assetType isEqualToString:ALAssetTypePhoto]) {
                DDFileInfo *fileInfo = [[DDFileInfo alloc]init];
                
                NSLog(@"Photo");
                NSDictionary *assetUrls = [result valueForProperty:ALAssetPropertyURLs];
                NSDictionary *test = [result valueForProperty:ALAssetPropertyRepresentations];
                NSLog(@"name------%@",[[result valueForProperty:ALAssetPropertyRepresentations]objectAtIndex:0]);
                NSUInteger assetCounter = 0;
                for (NSString *assetURLKey in assetUrls) {
                    NSLog(@"Asset URL %lu = %@",(unsigned long)assetCounter,[assetUrls objectForKey:assetURLKey]);
                    [fileInfo setFilePath:[assetUrls objectForKey:assetURLKey]];
                    [fileInfo setFileLength:[[result defaultRepresentation]size]];
                    NSURL *url= (NSURL*) [[result defaultRepresentation]url];
                    [fileInfo setUrl:url];
                    [fileInfo setFileId:[DDConstants getGloalId]];
                    int nextId = [DDConstants getGloalId] + 1;
                    NSString* fileName = [[result defaultRepresentation]filename];
                    [fileInfo setFileName:fileName];
                    [DDConstants setGloalId:nextId];
                    [DDConstants addFile:fileInfo andCode:LOCAL_CODE];
                    [[photoInfo files]addObject:fileInfo];
                    [photoInfo setCount:([photoInfo count] + 1)];
                    NSLog(@"fileName----------%@",[[result defaultRepresentation]filename]);
                }
            }else if([assetType isEqualToString:ALAssetTypeVideo]){
                NSLog(@"Video");
            }else if([assetType isEqualToString:ALAssetTypeUnknown]){
                NSLog(@"Unknow AssetType");
            }
            
        }
         ];
        if(group == nil){
            NSLog(@"stop---------%p",stop);
            [allFiles setObject:photoInfo atIndexedSubscript:0];
            [DDConstants setSharedLocalFolderInfos:allFiles];
            dispatch_async(dispatch_get_main_queue(),completion);
            return;
        }
        
    } failureBlock:^(NSError *error) {
        NSLog(@"Enumerate the asset groups failed.");
    }];
    
    
    return allFiles;
}

+ (BOOL)writeImage:(ALAsset*)asset toFileAtPath:(NSString*)aPath

{
    ALAssetRepresentation *rep = [asset defaultRepresentation];
    Byte *buffer = (Byte*)malloc(rep.size);
    NSUInteger buffered = [rep getBytes:buffer fromOffset:0 length:rep.size error:nil];
    NSData *data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];//this is NSData may be what you want
    [data writeToFile:aPath atomically:YES];
//    [data release];
    return NO;
}


-(void)dealloc{
    [_fileManager release];
    [super release];
}


@end
